package globe

import (
	"fmt"
	"github.com/go-redis/redis"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"oa_kadia_link/config"
	"oa_kadia_link/utils"
)

var rdb *redis.Client
var mdb *gorm.DB

func init() {
	rdb = redis.NewClient(&redis.Options{
		Addr:     config.GetRedis().Host + ":" + config.GetRedis().Port,
		Password: config.GetRedis().Password,
		DB:       config.GetRedis().DB,
	})

	_, err := rdb.Ping().Result()
	utils.CheckError(err)

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", config.GetMySQL().User, config.GetMySQL().Password, config.GetMySQL().Host, config.GetMySQL().Port, config.GetMySQL().DB)
	mdb, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	utils.CheckError(err)
	mdb = mdb.Clauses(clause.Locking{
		Strength: "SHARE",
		Table:    clause.Table{Name: clause.CurrentTable},
	})
}

func GetRdb() *redis.Client {
	return rdb
}

func GetMdb() *gorm.DB {
	return mdb
}

func CloseDB() error {
	return rdb.Close()
}

func RequestIpIncr(ip string) int64 {
	key := utils.ToRequestIp(ip)
	cnt, _ := GetRdb().Incr(key).Result()
	if cnt <= 1 {
		GetRdb().Expire(key, utils.ToTimeSecond(config.GetStorageTime().Ip))
	}
	return cnt
}

func FailIpIncr(ip string) int64 {
	key := utils.ToFailIp(ip)
	cnt, _ := GetRdb().Incr(key).Result()
	if cnt <= 1 {
		GetRdb().Expire(key, utils.ToTimeSecond(config.GetStorageTime().Ip))
	}
	return cnt
}
